<template>
  <div class="wrapper">
    <u-form label-width="200" :model="form" ref="uForm">
      <div class="column">
        <div class="flag-title light-color">{{title }}</div>
        <u-form-item
            required
            :border-bottom="false"
            prop="storeName"
            label="店铺名称"
        ><u-input v-model="form.storeName" :custom-style="defaultInputStyle"
        /></u-form-item>
        <u-form-item
            required
            :border-bottom="false"
            prop="storeLogo"
            label="店铺logo"
        >
          <div>
            <u-upload
                :file-list="storeLogoFileList"
                :header="{ accessToken: storage.getAccessToken() }"
                :action="action"
                width="200"
                @on-uploaded="onUploaded($event, 'storeLogo')"
                :max-count="1"
                :show-progress="false"
            ></u-upload>
          </div>
        </u-form-item>
        <u-form-item
            required
            :border-bottom="false"
            prop="storeType"
            label="店铺类型"
        >
          <div @click="showCategory()"   style="margin-right: 30rpx;">选择</div>

          <u-input
              :custom-style="defaultInputStyle"
              v-model="form.storeType"
              disabled
              @click="showCategory()"
          /></u-form-item>


<!--        店铺分类 select-->
        <u-form-item
            required
            :border-bottom="false"
            v-show="scStatus"
            prop="storeCategory"
            label="经营类目"
        >
          <div @click="showCategory2()"   style="margin-right: 30rpx;">选择</div>

          <u-input
              :custom-style="defaultInputStyle"
              v-model="form.storeCategory"
              disabled
              @click="showCategory2()"
          /></u-form-item>




        <u-form-item
            required
            :border-bottom="false"
            prop="storeAddressPath"
            label="所在地区"
        >
          <div @click="showPicker()"   style="margin-right: 30rpx;">选择</div>
          <u-input
              :custom-style="defaultInputStyle"
              v-model="form.storeAddressPath"

              disabled

          />
        </u-form-item>

        <!-- <u-form-item
          required
          :border-bottom="false"
          prop="storeAddressPath"
          label="店铺定位"
        >
          <div class="get-center" @click="clickUniMap()">开始定位</div>
          <div class="tips-success" v-if="form.storeCenter">已成功定位</div>
        </u-form-item> -->

        <u-form-item
            required
            :border-bottom="false"
            prop="storeAddressDetail"
            label="店铺详细地址"
        ><u-input
            :custom-style="defaultInputStyle"
            v-model="form.storeAddressDetail"
        /></u-form-item>

        <u-form-item
            required
            :border-bottom="false"
            prop="clerkName"
            label="店长姓名"
        ><u-input
            :custom-style="defaultInputStyle"
            v-model="form.clerkName"
        /></u-form-item>

        <u-form-item
            required
            :border-bottom="false"
            prop="clerkPhone"
            label="联系方式"
        ><u-input
            :custom-style="defaultInputStyle"
            v-model="form.clerkPhone"
        /></u-form-item>

        <u-form-item
            required
            :border-bottom="false"
            prop="storeStartTime"
            label="营业时间"
        >
          <view class="dateBtn" >
            <u-input
                :custom-style="defaultInputStyle"
                v-model="form.storeStartTime"
                class="date-input"
                @click="startDateClick"
                placeholder="开始时间"
            />
            <!--            <u-icon name="arrow-right" class="date-icon"></u-icon>-->
          </view>
          -
          <view class="dateBtn" >
            <u-input
                :custom-style="defaultInputStyle"
                v-model="form.storeEndTime"
                class="date-input"
                @click="endDateClick"
                placeholder="结束时间"
            />
            <!--            <u-icon name="arrow-right" class="date-icon"></u-icon>-->
          </view>
        </u-form-item>

        <u-form-item
            :border-bottom="false"
            prop="licencePhoto"
            label="营业执照电子版"

        >

          <div>
            <u-upload
                :file-list="licencePhotoFileList"
                :header="{ accessToken: storage.getAccessToken() }"
                :action="action"
                width="200"
                @on-uploaded="onUploaded($event, 'licencePhoto')"
                :max-count="1"
                :show-progress="false"
            ></u-upload>

            <!--            <div class="tips">-->
            <!--              请压缩图片在2M以内，确保文字清晰以免上传或审核失败-->
            <!--            </div>-->
          </div>
        </u-form-item>

        <!-- 新增审核输入框 -->
        <u-form-item

            :border-bottom="false"
            prop="auditComment"
            label="审核意见"
            v-if="form.storeDisable==='REFUSED' || form.storeDisable==='APPLYING' "
        ><u-input
            :custom-style="defaultInputStyle"
            v-model="form.auditComment"
            placeholder="请输入审核意见"
        /></u-form-item>

        <!-- 同意和拒绝按钮 -->
        <div class="button-container"  v-if="(form.storeDisable==='REFUSED' || form.storeDisable==='APPLYING') && role">
          <button class="agree-button" @click="enableStore(form.id)">同意</button>
          <button class="refuse-button" @click="refusedStore(form.id)">拒绝</button>
        </div>

      </div>
    </u-form>
    <div class="submit" @click="validatorStep1Form" v-if="form.storeDisable!='APPLYING'">{{undefined!=type?'提交保存':'提交平台审核'}}</div>
    <m-city
        :provinceData="list"
        headTitle="区域选择"
        ref="cityPicker"
        @funcValue="getPickerParentValue"
        pickerSize="4"
    >
    </m-city>

    <u-select
        v-model="enableCategory"
        @confirm="confirmCategory"
        :list="categoryList"
    ></u-select>

    <u-select
        v-model="enableCategory2"
        @confirm="confirmCategory2"
        :list="categoryList2"
    ></u-select>



    <uniMap v-if="mapFlag" @close="closeMap" @callback="callBackAddress" />


    <u-picker mode="time" v-model="showStart" :params="params" @confirm="changeStartDate"></u-picker>
    <u-picker mode="time" v-model="showEnd" :params="params" @confirm="changeEndDate"></u-picker>


    <!--    <u-calendar v-model="show" :mode="'time'" @change="changeDate" max-date="2100-01-01"></u-calendar>-->
  </div>
</template>

<script>
import { applyStep, } from "@/api/entry";
import {getStoreByMember,auditStore, disableStore, enableStore,refusedStore} from "@/api/store";
import { getCategoryList,getCategoryList2 } from "@/api/goods";
import city from "@/components/m-city/m-city.vue";
import storage from "@/utils/storage.js";
import { upload } from "@/api/common.js";
import uniMap from "@/components/uniMap";
import permision from "@/js_sdk/wa-permission/permission.js";
export default {
  components: { "m-city": city, uniMap },
  name: "addStore",
  data() {
    return {
      storage,
      role:false,
      scStatus:false,
      title:'',
      mapFlag: false,
      showStart: false,
      showEnd: false,
      params: {
        hour: true,
        minute: true
      },
      dateLabel:'',
      action: upload, //图片上传数据
      defaultInputStyle: {
        background: "#f7f7f7",
        padding: "0 20rpx",
        "border-radius": "10rpx",
      },
      storeCategoryId: "",
      storeLogoFileList: [],
      licencePhotoFileList: [],
      categoryList: [],
      storeId: "",
      form: {
        storeName: "",
        storeLogo: "",
        storeCategoryId: "",
        storeAddressPath: "",
        storeAddressDetail: "",
        storeDesc: "",
        storeType:"",
        storeTypeId:'',
        clerkName: "",
        clerkPhone: "",
        storeCenter: "",
        storeAddressIdPath: "",
        storeId: "",
        licencePhoto: "",
        storeStartTime: "",
        storeEndTime: "",
        auditComment:"",
        storeCategory:''
      },
      userInfo:{},
      type:"",
      list: [
        {
          id: "",
          localName: "请选择",
          children: [],
        },
      ],
      rules: {
        // 验证规则
        storeCategoryId: [
          { required: true, message: "请选择店铺经营类目" },
        ],
        storeName: [{ required: true, message: "请填写店铺名称" }],
        storeLogo: [{ required: true, message: "请上传店铺logo" }],
        storeDesc: [{ required: true, message: "请填写店铺简介" }],
        storeCenter: [{ required: true, message: "请选择店铺位置" }],
        storeAddressIdPath: [{ required: true, message: "请选择店铺位置" }],
        storeAddressDetail: [{ required: true, message: "请输入店铺详细地址" }],
        storeStartTime: [{ required: true, message: "请选择营业时间开始时间" }],
        storeAddressPath: [{ required: true, message: "请选择所在区域" }],
        storeType: [{ required: true, message: "请选择店铺类型" }],
        storeEndTime: [{ required: true, message: "请选择营业时间结束时间" }]
      },
      enableCategory: false,
      enableCategory2:false,
      categoryList2:[]
    };
  },
  mounted() {
    if (this.$options.filters.tipsToLogin()) {
      this.$refs.uForm.setRules(this.rules);
      this.fetchCategoryList();
    }

  },
  onLoad(options){
    this.type=options.type
    if(options.memberId==undefined){
      //   this.title2="自己"
      this.userInfo=storage.getUserInfo();
      this.storeId=this.userInfo.id;
      // this.getStoreByMember(userInfo.id);
    }else{
      this.role=true
      // this.title2="管理员"
      this.storeId=options.memberId
      //this.getStoreByMember(options.memberId);
    }

    this.getStoreByMember( this.storeId);
  },
  //props: ["companyData"],
  watch: {
    // companyData: {
    //   handler(val) {
    //     this.$set(this, "form", val);
    //     // 给图片赋值
    //     const judgeDeepPhoto = ["storeLogo"];
    //
    //     judgeDeepPhoto.forEach((key) => {
    //       if (this.form[key]) {
    //         this.form[key].split(",").forEach((item) => {
    //           this[`${key}FileList`].push({ url: item });
    //         });
    //       }
    //     });
    //   },
    //   deep: true,
    //   immediate: true,
    // },
  },

  methods: {
    startDateClick(){
      this.showStart = true
    },
    endDateClick(){
      this.showEnd = true
    },
    changeStartDate(e){
      var  time=e.hour+":"+e.minute;
      this.form.storeStartTime = time
    },
    changeEndDate(e){
      var  time=e.hour+":"+e.minute;
      this.form.storeEndTime = time
    },

    getStoreByMember(id){
      getStoreByMember(id).then(res=>{
        if(res.data==''){
          return
        }
        this.licencePhotoFileList=[]
        this.storeLogoFileList=[]
        console.log(res);
        var data=res.data
        this.form.storeName = data.storeName;
        this.form.storeLogo = data.storeLogo;
        this.form.storeCategoryId = data.storeCategoryId;
        this.form.storeAddressDetail = data.storeAddressDetail;
        this.form.storeAddressPath = data.storeAddressPath;
        this.form.storeDesc = data.storeDesc;
        this.form.storeAddressIdPath = data.storeAddressIdPath;
        this.form.storeCenter = data.storeCenter;
        this.form.clerkName = data.clerkName;
        this.form.clerkPhone = data.clerkPhone;
        this.form.storeType=data.storeType

        this.form.licencePhoto = data.licencePhoto;
        this.form.storeStartTime = data.storeStartTime;
        this.form.storeEndTime = data.storeEndTime;
      //  this.form.storeEndTime = data.storeEndTime;
        this.form.id=data.id;
        //店铺状态：storeDisable------>APPLYING：待审核，OPEN：已审核，REJECTED： 审核不通过  关闭店铺:CLOSED
        this.form.storeDisable=data.storeDisable
        this.form.auditComment=data.auditComment

        if(this.form.storeDisable==='APPLYING'){
          //提示审核中
          this.title="店铺审核中"
        }else if(this.form.storeDisable==='OPEN'){

          if( this.type!="1"){
            //提示审核通过
            this.title="店铺审核通过"
            uni.navigateTo({
              url: "/pages/manage/sub/shopInfo"
            });
          }

        }else if(this.form.storeDisable==='REFUSED'){
          //提示审核不通过
          this.title="店铺审核已被管理员拒\n请根据拒绝原因进行修改"
        }else if(this.form.storeDisable==='CLOSED'){
          //提示店铺已关闭
          this.title="店铺已关闭"
        }

        // 给图片赋值
        const judgeDeepPhoto = ["storeLogo","licencePhoto"];
        judgeDeepPhoto.forEach((key) => {
          if (this.form[key]) {
            this.form[key].split(",").forEach((item) => {
              this[`${key}FileList`].push({ url: item });
            });
          }
        });
      })
    },
    callBackAddress(val) {
      console.log(val);
      this.form.storeAddressDetail = val.address;
      this.form.storeCenter = `${val.longitude},${val.latitude}`;
    },
    // 关闭地图
    closeMap() {
      this.mapFlag = false;
    },
    // 打开地图并访问权限
    clickUniMap() {
      console.log("click");
      // #ifdef APP-PLUS
      if (plus.os.name == "iOS") {
        // ios系统
        permision.judgeIosPermission("location")
            ? (this.mapFlag = true)
            : this.refuseMap();
      } else {
        // 安卓
        this.requestAndroidPermission(
            "android.permission.ACCESS_FINE_LOCATION"
        );
      }
      // #endif

      // #ifndef APP-PLUS
      this.mapFlag = true;
      // #endif
    },

    // 如果拒绝权限 提示区设置
    refuseMap() {
      uni.showModal({
        title: "温馨提示",
        content: "您已拒绝定位,请开启",
        confirmText: "去设置",
        success(res) {
          if (res.confirm) {
            //打开授权设置
            // #ifndef MP-WEIXIN
            uni.getSystemInfo({
              success(res) {
                if (res.platform == "ios") {
                  //IOS
                  plus.runtime.openURL("app-settings://");
                } else if (res.platform == "android") {
                  //安卓
                  let main = plus.android.runtimeMainActivity();
                  let Intent = plus.android.importClass(
                      "android.content.Intent"
                  );
                  let mIntent = new Intent("android.settings.ACTION_SETTINGS");
                  main.startActivity(mIntent);
                }
              },
            });
            // #endif
          }
        },
      });
    },
    // 获取安卓是否拥有地址权限
    async requestAndroidPermission(permisionID) {
      var result = await permision.requestAndroidPermission(permisionID);

      if (result == 1) {
        this.mapFlag = true;
      } else {
        this.refuseMap();
      }
    },
    confirmCategory2(val){
      this.form.storeCategoryId=val[0].value
      this.form.storeCategory=val[0].label
    },
    confirmCategory(val) {


      //storeCategoryId
      this.form.storeCategory='';
      this.form.storeCategoryId='';

      this.form.storeTypeId=val[0].value
      this.form.storeType = val[0].label;
      this.storeType = val[0].label;
      if(val[0].label==='房产中介'){

        this.form.storeCategoryId=val[0].value
      }

      //getCategoryList2
      getCategoryList2(this.form.storeTypeId).then(res=>{

        if (res.data.success) {
          if (res.data.result.length) {
                this.scStatus=true;
            this.categoryList2 = res.data.result.map((item) => {
              return { label: item.name, value: item.id };
            });

          }else{
            this.scStatus=false;
          }
        }
      })


    },
    async fetchCategoryList() {
      const res = await getCategoryList(0);
      if (res.data.success) {
        if (res.data.result.length) {

          this.categoryList = res.data.result.map((item) => {
            return { label: item.name, value: item.id };
          });

        }
      }
    },
    // 图片上传
    onUploaded(lists, key) {
      let images = [];
      lists.forEach((item) => {
        images.push(item.response.result);
      });
      this.form[key] = images;


    },
    getPickerParentValue(e) {
      this.form.storeAddressIdPath = [];
      console.log(e)
      let name = "";
      e.forEach((item, index) => {
        if (item.id) {
          // 遍历数据
          this.form.storeAddressIdPath.push(item.id);
          if (index == e.length - 1) {
            name += item.localName;
          } else {
            name += item.localName + ",";
          }
          this.$set(this.form,'storeAddressPath',name)
        }
      });

      this.form.storeCenter = e[e.length-1].center
    },
    // 显示三级地址联动
    showPicker() {
      this.$refs.cityPicker.show();
    },
    showCategory() {
      this.enableCategory = true;
    },
    showCategory2() {
      this.enableCategory2 = true;
    },
    validatorStep1Form() {
      this.$refs.uForm.validate(async (valid) => {
        console.log(valid);
        if (valid) {
          // 校验开始与结束时间
          if (!this.form.storeStartTime || !this.form.storeEndTime) {
            uni.showToast({
              title: "请选择营业时间的开始和结束时间",
              icon: "none"
            });
            return;
          }
          const startTime = new Date(`2000-01-01 ${this.form.storeStartTime}`);
          const endTime = new Date(`2000-01-01 ${this.form.storeEndTime}`);
          if (startTime >= endTime) {
            uni.showToast({
              title: "结束时间不能早于开始时间",
              icon: "none"
            });
            return;
          }

          const params = { ...this.form };
          params.storeLogo = params.storeLogo.toString();

          if(params.licencePhoto.length>0){
            params.licencePhoto=params.licencePhoto[0];
          }
          params.storeAddressIdPath = params.storeAddressIdPath.toString();

          const res = await applyStep(params);

          if (res.data.success) {

            uni.showToast({
              title: "提交成功!",
              icon: "none",
            });
            //延时
            setTimeout(() => {
              this.getStoreByMember(this.storeId);
              // uni.navigateTo({
              //   url: "/pages/manage/sub/shopInfo",
              // });
            }, 1000);
            // this.$emit("callback");
          }else{
            uni.showToast({
              title: res.data.message,
              icon: "none",
            });
          }
        }
      });
    },
    enableStore(id) {

      enableStore(id).then(res => {
        if(res.data.success){
          this.getStoreByMember( this.storeId);
        }
      });
      // 处理同意逻辑
      console.log('同意操作');
    },
    refusedStore(id) {

      refusedStore(id,this.form.auditComment).then(res => {
        if(res.data.success){
          this.getStoreByMember( this.storeId);
        }

      });
      // 处理拒绝逻辑
      console.log('拒绝操作');
    }
  },
};
</script>
<style>
/* page {
  background: #fff;
} */
</style>
<style lang="scss" scoped>
//@import url("./entry.scss");
.get-center {
  padding: 12rpx 30rpx;
  background: $light-color;
  border-radius: 10rpx;
  font-size: 28rpx;
  color: #fff;
  font-weight: bold;
  display: inline;
}
.column {
  padding: 32rpx;
  margin-bottom: 20rpx;
  background: #fff;
}
.submit {
  color: #fff;
  margin-top: 120rpx;
  background: rgba($light-color, 0.8);
}
.tips {
  color: #999;
  font-size: 28rpx;
  line-height: 1.2;
  margin-top: 10rpx;
}
.tips-success {
  color: $weChat-color;
  font-size: 28rpx;
}


.flag-title {
  font-size: 42rpx;
  font-weight: bold;
}
.submit,
.notice {
  font-weight: bold;
  font-size: 28rpx;

  height: 92rpx;
  text-align: center;
  letter-spacing: 4rpx;
  line-height: 92rpx;
  border-radius: 20rpx;
}
.wrapper {
  padding:16rpx;
}
.dateBtn {
  display: flex; /* 使用 flex 布局 */
  align-items: center; /* 垂直居中对齐 */
  justify-content: space-between; /* 水平方向两端对齐 */
  padding: 10rpx; /* 可根据需要调整内边距 */
  // border: 1rpx solid #ccc; /* 可选：添加边框 */
  border-radius: 5rpx; /* 可选：添加圆角 */
}

.date-input {
  flex: 1; /* 让输入框占据剩余空间 */
  margin-right: 10rpx; /* 与图标之间留出一些间距 */
}

.date-icon {
  /* 可根据需要调整图标样式 */
}
.button-container {
  display: flex;
  justify-content: space-between;
  margin-top: 20rpx;
}
.agree-button,
.refuse-button {
  padding: 10rpx 20rpx;
  border: none;
  border-radius: 10rpx;
  font-size: 28rpx;
  font-weight: bold;
  color: #fff;
}
.agree-button {
  background-color: green;
}
.refuse-button {
  background-color: red;
}
</style>